import md5 from 'js-md5'

export function showToast(text) {
	if (!text) {
		return
	}
	uni.showToast({
		title: text,
		icon: "none",
		duration: 2000
	});
}

export function showLoading(title = '加载中') {
	uni.showLoading({
		title: title
	})
}

export function showModal(text) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: "提示",
			content: text,
			success: function(res) {
				if (res.confirm) {
					resolve();
				} else if (res.cancel) {
					reject();
				}
			}
		});
	})
}

export function navigateTo(url) {
	uni.navigateTo({
		url: url
	});
}

export function processData(dataUrl) {
	let arr = dataUrl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	let blob = new Blob([u8arr], {
		type: mime
	});
	return URL.createObjectURL(blob);
}

/**
 * 生成随机字符串
 * @param {Object} length 长度
 */
export function generateRandomString(length) {
	const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	return Array.from({
			length
		})
		.map(() => characters.charAt(Math.floor(Math.random() * characters.length)))
		.join('');
}
/**
 * 从本地相册选择图片或使用相机拍照
 */
export function chooseImage() {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			// 默认9
			sizeType: ['compressed'],
			// 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'],
			// 可以指定来源是相册还是相机，默认二者都有
			success: function(res) {
				resolve(res);
			}
		});
	});
}

/**
 * 上传文件
 * @param {Object} file
 */
export function uploadFile(file, data) {
	// 本地
	// let baseApi = 'http://k3n3211190.51vip.biz'
	// 测试
	// let baseApi = 'http://106.52.200.181:10010'
	// 正式
	let baseApi = 'http://hmzf-lg.yuemandata.com'
	let newData = setSignData('singleFileUpload', data)
	return new Promise((resolve, reject) => {
		showLoading('上传中')
		uni.uploadFile({
			url: `${baseApi}/api/entry`,
			filePath: file,
			name: 'file',
			formData: newData,
			success: (res) => {
				let data = JSON.parse(res.data)
				if (data.status != 'SUCCESS') {
					uni.hideLoading();
					setTimeout(() => {
						showToast(data.message || "上传失败")
					}, 10)
					reject(res)
				} else {
					resolve(data)
				}
			},
			fail: (err) => {
				showToast(err.message || '上传失败')
			},
			complete: () => {
				uni.hideLoading()
			}
		});
	});
}
/**
 * 生成签名
 */
export function setSignData(action, data) {
	// 随机字符串
	let str = generateRandomString(8)
	// 签名KEY
	let signKey = '0fe114c852f65cc985743f94421774c5'
	let newData = {
		...data,
		action: action,
		nonce_str: str
	}
	let sortedKeys = Object.keys(newData).sort();
	let objString = ''
	sortedKeys.forEach(key => {
		objString += `${key}=${newData[key]}&`
	});
	newData.sign = md5(`${objString}key=${signKey}`)
	return newData
}
/**
 * 图片压缩
 * @param {Object} path
 */
export function imageCompression(path) {
	return new Promise((resolve, reject) => {
		var img = new Image();
		img.src = path;
		img.onload = function() {
			var that = this;
			// 默认按比例压缩
			var originWidth = that.width,
				originHeight = that.height;
			// 最大尺寸限制
			const maxWidth = 1000;
			const maxHeight = 1000;
			// 目标尺寸
			let targetWidth = originWidth
			let targetHeight = originHeight
			if (originWidth > maxWidth || originHeight > maxHeight) {
				if (originWidth / originHeight > 1) {
					// 宽图片
					targetWidth = maxWidth
					targetHeight = Math.round(maxWidth * (originHeight / originWidth))
				} else {
					// 高图片
					targetHeight = maxHeight
					targetWidth = Math.round(maxHeight * (originWidth / originHeight))
				}
			}
			//生成canvas
			var canvas = document.createElement('canvas'),
				ctx = canvas.getContext('2d');
			canvas.width = targetWidth;
			canvas.height = targetHeight;
			ctx.drawImage(that, 0, 0, targetWidth, targetHeight);
			// 默认图片质量为0.7
			var quality = 0.5;
			// 回调函数返回base64的值
			var base64 = canvas.toDataURL('image/jpeg', quality);
			resolve(processData(base64));
		}
	})
}

export function getDateTime(time, cFormat) {
	if (!time) return '';
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (('' + time).length === 10) time = parseInt(time) * 1000
		if (('' + time).length != 13) {
			date = new Date(time.replace(/-/g, '/'))
		} else {
			date = new Date(time);
		}
	}
	let ret, timeStr;
	const opt = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	};
	for (let k in opt) {
		ret = new RegExp('(' + k + ')').exec(cFormat);
		if (ret) {
			let str = opt[k] + '';
			if (k != 'a') str = parseInt(str) >= 10 ? str : str.padStart(2, '0');
			cFormat = cFormat.replace(ret[1], str);
		}
	}
	return cFormat;
}